package array;
public class Array <E>{
	
	private E[] data;
	private int size;
	
	public Array (int capacity) {
		data = (E[])new Object[capacity];
		size = 0 ;
	}
	
	public Array () {
		//如果用户不传入数组的长度，那么则默认创建长度为10的数组
		this(10);
	}
	
	public int getCapacity() {
		return data.length;
	}
	
	
	public int getSize() {
		return size;
	}
	
	//返回数组是否为空
	public boolean isEmpty() {
		return size == 0;
	}
	
	//向最后一个元素的位置添加元素
	public void addLast(E e) {
		/*
		 * if(size == data.length) { throw new IllegalArgumentException(); } data[size]
		 * = e; size++;
		 */
		add(size,e);
	}
	
	//往指定的位置添加元素
	public void add(int index,E e) {
		if(index < 0 || index > size) {
			throw new IllegalArgumentException("add failed,index is error");
		}
		
		if(size == data.length) {
			resize(data.length * 2);
		}
		
		for(int i = size-1 ; i >= index ; i-- ) {
			data[i+1] = data[i];
		}
		data[index] = e;
		size++;
	}
	
	public void addFirst(E e) {
		add(0,e);
	}

	public void swap(int i , int j){
		if(i < 0 || i >= size || j < 0 || j >= size)
			throw new IllegalArgumentException("");
		E t = data[i];
		data[i] = data[j];
		data[j] = t;
	}
	@Override
	public String toString() {
		
		StringBuilder res = new StringBuilder();
		res.append(String.format("Array: size = %d,capacity = %d\n", size,data.length));
		res.append('[');
		for(int i = 0 ; i < size ; i++) {
			res.append(data[i]);
			if(i != size - 1) {
				res.append(",");
			}
		}
		res.append(']');
		return res.toString();
	}
	
	//获取index索引位置的值
	public E get(int index) {
		if(index < 0 || index >= size) {
			throw new IllegalArgumentException();
		}
		return data[index];
	}
	
	//获取数组第一个位置的元素的值
	public E getFirst() {
		return get(0);
	}
	
	//获取数组最后一个位置的元素的值
	public E getLast() {
		return get(size - 1);
	}
	
	//修改index索引位置元素的值
	public void set(int index,E e) {
		if(index < 0 || index >= size) {
			throw new IllegalArgumentException();
		}
		data[index] = e;
	}
	
	public boolean contains(E e) {
		for(int i = 0 ; i < size ; i++) {
			if(data[i] == e) {
				return true;
			}
		}
		return false;
	}
	
	public int find(E e) {
		for(int i = 0 ; i < size ; i++) {
			if(data[i] == e) {
				return i;
			}
		}
		return -1;
	}
	
	//从数组中删除index位置的元素，返回删除的元素
	public E remove(int index) {
		if(index < 0 || index >= size) {
			throw new IllegalArgumentException("remove failed");
		}
		E ret = data[index];
		for(int i = index + 1 ; i < size ; i++) {
			data[i - 1] = data[i];
		}
		size--;
		if(size == data.length/4) {
			resize(data.length/2);
		}
		return ret;
	}
	
	//删除数组中第一个元素
	public E removeFirst() {
		return remove(0);
	}
	
	//删除数组中最后一个位置的元素
	public E removeLast() {
		return remove(size-1);
	}
	
	//从数组中删除指定的元素
	public void removeElement(E e) {
		int index = find(e);
		if(index != -1) {
			remove(index);
		}
	}
	
	public void resize(int newCapacity) {
		E[] newData = (E[])new Object[newCapacity];
		for(int i = 0 ; i < size; i ++) {
			newData[i] = data[i];
		}
		data = newData;
	}
}
